<?php
/**
 * Created by PhpStorm.
 * User: anyuzhe
 * Date: 2017/3/26
 * Time: 15:06
 */

namespace App\Repositories;

use App\Models\Address;
use App\Models\Bonus;
use App\Models\Cart;
use App\Models\GoodsEvaluate;
use App\Models\GoodsNumberLog;
use App\Models\IntegralLog;
use App\Models\Order;
use App\Models\PayRecord;
use App\Models\ReturnLog;
use App\User;
use App\ZL\Library\Curl;
use App\ZL\Library\ErrorCode;
use App\ZL\Library\Openssl;
use Illuminate\Support\Facades\DB;
use InfyOm\Generator\Common\BaseRepository;
use Illuminate\Support\Collection;
use Illuminate\Container\Container as App;

class UsersRepository extends BaseRepository {

    protected $store;

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function model() {
        return 'App\User';
    }

    public function checkHasAndSaveInfo($user, $shop_id=null)
    {
        $json = json_encode($user,256);
        $_user = $user;
        $user['nickName'] = isset($user['nickname'])?$user['nickname']:$user['nickName'];
        if(isset($user['openid']))
            $openId = $user['openid'];
        else
            $openId = $user['openId'];
        if(isset($_user['unionid'])){
            $user['unionId'] = $_user['unionid'];
        }elseif (isset($_user['unionId'])){
            $user['unionId'] = $_user['unionId'];
        }else{
            $user['unionId'] = null;
        }
        $user['avatarUrl'] = isset($user['headimgurl'])?$user['headimgurl']:$user['avatarUrl'];
        $user['gender'] = isset($user['sex'])?$user['sex']:$user['gender'];
        $user['shop_id'] = $shop_id;
        $hasuser = $this->checkHas(isset($user['unionId'])?$user['unionId']:$openId,isset($user['unionId']),$openId,$shop_id);

        if($hasuser && isset($user['unionId'])){
            $find_openid = $this->getOneByOpenid($openId,true, $shop_id);
            if($hasuser->id!=$find_openid->id){
                Bonus::where('user_id',$find_openid->id)->update(['user_id'=>$hasuser->id]);
                Cart::where('user_id',$find_openid->id)->update(['user_id'=>$hasuser->id]);
                GoodsEvaluate::where('user_id',$find_openid->id)->update(['user_id'=>$hasuser->id]);
                GoodsNumberLog::where('user_id',$find_openid->id)->update(['user_id'=>$hasuser->id]);
                IntegralLog::where('user_id',$find_openid->id)->update(['user_id'=>$hasuser->id]);
                Address::where('user_id',$find_openid->id)->update(['user_id'=>$hasuser->id]);
                //订单
                Order::where('user_id',$find_openid->id)->update(['user_id'=>$hasuser->id]);
                Order::where('pairing_id',$find_openid->id)->update(['pairing_id'=>$hasuser->id]);
                Order::where('verifier_id',$find_openid->id)->update(['verifier_id'=>$hasuser->id]);
                Order::where('courier_id',$find_openid->id)->update(['courier_id'=>$hasuser->id]);

                PayRecord::where('payer_id',$find_openid->id)->update(['payer_id'=>$hasuser->id]);
                DB::table('role_user')->where('user_id',$find_openid->id)->update(['user_id'=>$hasuser->id]);
                DB::table('messages')->where('user_id',$find_openid->id)->update(['user_id'=>$hasuser->id]);
                DB::table('messages_history')->where('created_id',$find_openid->id)->update(['created_id'=>$hasuser->id]);

                $hasuser->integral+=$find_openid->integral;
                $hasuser->save();
                $find_openid->delete();
            }
        }
        $data = [
            'nickname'=>$user['nickName'],
            'shop_id'=>$user['shop_id'],
            'avatar_url'=>$user['avatarUrl'],
            'sex'=>$user['gender'],
            'unionid'=>$user['unionId'],
            'city'=>$user['city'],
            'session_id'=>getSessionId(),
            'json'=>$json,
        ];
        if(isset($user['openid']))
            $data['openid'] = $user['openid'];
        if(isset($user['openId']))
            $data['xcx_openid'] = $user['openId'];

        if(!$hasuser){
            $new = $this->create($data);
//            $bonus = Bonus::where('name','新用户满减券')->where('user_id',0)->first();
//            $bonus->user_id = $new->id;
//            $bonus->save();
            return $new->id;
        }else{
            $this->update($data,$hasuser->id);
            return $hasuser->id;
        }
    }

    public function checkHasAndSaveInfoByWechat($user)
    {
        saveNotification($user,'userinfowechat');
        $hasuser = $this->checkHas($user['unionid']);

        $data = [
            'openid'=>$user['openid'],
            'nickname'=>$user['nickname'],
            'avatar_url'=>$user['headimgurl'],
            'sex'=>$user['sex'],
            'unionid'=>$user['unionid'],
            'city'=>$user['city'],
            'session_id'=>getSessionId(),
        ];
        if(!$hasuser){
            $new = $this->create($data);
////            $bonus = Bonus::where('name','新用户满减券')->where('user_id',0)->first();
////            $bonus->user_id = $new->id;
////            $bonus->save();
            return $new->id;
        }else{
            $this->update($data,$hasuser['id']);
            return $hasuser['id'];
        }
    }

    public function getOneByOpenid($openId,$is_xcx=true,$shop_id=null)
    {
        if($is_xcx)
            $field = 'xcx_openid';
        else
            $field = 'openid';
            return User::where($field,$openId)->where('shop_id', $shop_id)->first();
    }

    public function saveToken($id,$sessionKey)
    {
        $this->update(['remember_token'=>$sessionKey],$id);
    }

    public function saveTokenAndGetSecret($id,$sessionKey)
    {
        $this->saveToken($id,$sessionKey);
        $data = ['id'=>$id,'remember_token'=>$sessionKey];
        $key = config('app.aes_key');
        $iv = config('app.aes_iv');
        $encrypted = Openssl::encryptByAes($key,$iv,json_encode($data));
        return base64_encode($encrypted);
    }

    public function checkHas($unionid,$is_unionid=true,$openid=null,$shop_id=null)
    {
        if($is_unionid){
            $_r = User::where('unionid',$unionid)->where('shop_id',$shop_id)->first();
            if($_r)
                return $_r;
            if($openid)
                return $this->getOneByOpenid($openid,true,$shop_id);
            else
                return null;
        }else
            return $this->getOneByOpenid($openid,true,$shop_id);
    }

    public function checkHasAndSaveGetInfoByWechat($access_token,$openid,$unionid,$save=true)
    {
        $user = $this->checkHas($unionid);
        if(!$save){
            return $user;
        }
        if(!$user || !$user['nickname'] || !$user['openid']){
            $userinfo = $this->getUserInfoByWechat($access_token,$openid);
            if($userinfo){
                $userinfo['id'] = isset($user['id'])?$user['id']:null;
                $this->checkHasAndSaveInfoByWechat($userinfo);
            }
        }
        return $this->checkHas($unionid);
    }
    public function getUserInfoByWechat($accessToken,$openId)
    {
//        $app = new Application(c('easywechat_config'));
//        // 获取用户实例
//        $userService = $app->user;
//        return $userService->get($openId);
        //通过网页授权access_token和openid获取用户基本信息（支持UnionID机制）
        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$accessToken.'&openid='.$openId.'&lang=zh_CN';
        //转成对象
        $user_info = json_decode(Curl::get($user_info_url),true);
        $this->qc = $user_info;
        $weixin_openid = $user_info['openid'];
        if(!isset($weixin_openid)){
            echo '信息获取失败，请返回刷新后重新操作';die;
        }
        return $user_info;
    }
}